﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    class UrlMoniker: UrlData{
        public static Guid UrlClsid = new Guid(0x79EAC9E0, 0xBAF9, 0x11CE, 0x8C, 0x82, 0x00, 0xAA, 0x00, 0x4B, 0xA9,
                                               0x0B);

        private Guid? serialGUID;
        private uint serialVersion;
        private uint uriFlags;
        private string url;

        public string Url
        {
            get { return url; }
            set { url = value; }
        }

        public override void Read(BinaryReader reader)
        {
            var length = reader.ReadUInt32();
            List<char> chars = new List<char>();
            char c = (char) reader.ReadUInt16();
            while (c != '\0')
            {
                chars.Add(c);
                c = (char)reader.ReadUInt16();
            }
            this.url = new string(chars.ToArray());
            var strLength = 2*chars.Count + 2;
            if (length == strLength)
                return;
            Contract.Assert(length == strLength + 24);
            this.serialGUID = new Guid(reader.ReadBytes(16));
            this.serialVersion = reader.ReadUInt32();
            this.uriFlags = reader.ReadUInt32();
        }

        public override void Write(BinaryWriter writer)
        {
            uint length = (uint)(2 * url.Length + 2);
            if (serialGUID != null)
                length += 24;
            writer.Write(length);
            foreach (var c in this.url)
            {
                writer.Write((ushort)c);
            }
            writer.Write((ushort)'\0');
            if (serialGUID == null)
                return;
            writer.Write(serialGUID.Value.ToByteArray());
            writer.Write(serialVersion);
            writer.Write(uriFlags);
        }

        public override Guid Clsid
        {
            get { return UrlClsid; }
        }
    }
}